package com.ysmygx.cosumer;

import cn.hutool.core.lang.UUID;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ysmygx.constants.AuthConstants;
import com.ysmygx.entity.AccountTransHisReq;
import com.ysmygx.entity.AccountTransHisResp;
import com.ysmygx.manage.BankManage;
import com.ysmygx.utils.BusinessException;
import com.ysmygx.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Value;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author laoyanbin
 */
@Slf4j
@Service
@RocketMQMessageListener(topic = "query-bank-flow-topic", consumerGroup = "query_bank_flow_consumer")
public class QueryBankFlowConsumer implements RocketMQListener<String> {

    @Resource
    private BankManage bankManage;

    @Value("${ysmygx.cloud.queryBankFlowCallBackUrl}")
    private String callBackUrl;

    @Override
    public void onMessage(String message) {
        ThreadLocalUtil.set(UUID.fastUUID().toString(true));
        log.info("{},接收到查询银行流水消息：{}",ThreadLocalUtil.get(), message);
        try {
            AccountTransHisReq transHisReq = JSONUtil.toBean(JSONUtil.parseObj(message).getStr("body"), AccountTransHisReq.class);

            //分页查询，每页500条，直到返回空
            int currentPage = 1;
            int pageSize = 500;

            transHisReq.setTurnPageShowNum(String.valueOf(pageSize));//每页条数
            //交易方式（借贷标志）A:全部，D:支取（借），C:存入（贷）
            transHisReq.setTranKind("A");
            transHisReq.setHistKind("0");


            while (true){
                String pageBeginPos = String.valueOf ((currentPage-1) * pageSize);
                transHisReq.setTurnPageBeginPos(pageBeginPos);//分页开始位置

                AccountTransHisResp data = bankManage.queryAccountTransHis(transHisReq);

                if (data.getITranHistInfoCopy() == null || data.getITranHistInfoCopy().isEmpty()){
                    //没有数据的时候跳出循环
                    break;
                }

                //调用回调接口，把银行流水数据发送到服务器
                String bodyJsonStr = JSONUtil.toJsonStr(data);
                HttpResponse httpResponse = HttpRequest.post(callBackUrl).header("appid", AuthConstants.APPID).body(bodyJsonStr).execute();
                if (!httpResponse.isOk() || JSONUtil.parseObj(httpResponse.body()).getInt("code")!=200){
                    log.error("请求银行流水回调失败:{}", httpResponse.body());
                    throw new BusinessException("请求回调url异常");
                }



                if (data.getITranHistInfoCopy().size() < pageSize){
                    //最后一页
                    break;
                }

                //页数+1
                currentPage++;
            }
        }catch (Exception e){
            log.error("银行流水消息消费异常",e);
        }
    }
}






